<?php
declare (strict_types=1);

namespace app\middleware;

use app\traits\JsonResponse;
use think\facade\Cache;

class RateLimit {
    use JsonResponse;
    public function handle($request, \Closure $next,$maxTime=60) {
        $maxTimes = $maxTime;
        $perTime = 1;
        $key = 'rate_'.$request->ip();
        $clickTime = Cache::get($key,0);
        if($clickTime >= $maxTimes){
            return $this->jsonFail(message:'访问次数过多',httpCode:429);
        }
        Cache::set($key,$clickTime+1, $perTime*60);
        return $next($request);
    }
}
